<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 9:39
 */

namespace app\index\controller;


use think\Request;
use think\cache;

class Role extends Backend
{
    /**
     * 管理列表
     */
    public function tel($id=0)
    {
        
        
        $title=db('relation')->where('role_id', $id)->field('user_id')->select();
        
        $s='';
        foreach ($title as $key=>$val) {
            $s.=$val["user_id"] . ',';
        }
        $s=substr($s, 0, - 1);
        
        $data=db('admin')->where(['admin_id'=>['in', $s]])->paginate(10);
        return $this->fetch('tel', ['data'=>$data]);
    }
    
    
    /**
     * @return array|mixed|string
     * 添加管理
     */
    public function add()
    {
        if ($data=Request::instance()->post()) {
            if (empty($data['rule'])) {
                return json_data([], 300, '请选择类别');
            }
            if ($data['rule'] == 9) {
                $mobile=$data['mobile'];
            } else{
                $mobile='';
            }
            $s =0;
            $s1=0;
            if (!empty($data['qu'])) {
                $s='';
                foreach ($data['qu'] as $key=>$val) {
                    $s.=$val . ',';
                }
                $s=substr($s, 0, - 1);
            }
            if (!empty($data['residential_id'])) {
                $s1='';
                foreach ($data['residential_id'] as $key=>$val) {
                    $s1.=$val . ',';
                }
                $s1=substr($s1, 0, - 1);
            }
            $user=[
                'username'      =>$data['username'],
                'password'      =>encrypt($data['password']),
                'created_time'  =>time(),
                'logo'          =>!empty($data['logo'])? $data['logo'] : '',
                'status'        =>0,
                'mobile'        =>$mobile,
                'store_id'      =>$data['store_id'],
                'qu'            =>$s,
                'residential_id'=>$s1,
                'hide'          =>$data['hide'],
                'personal_id'   =>empty($data['personal_id'])?0:$data['personal_id'],
            
            
            ];
            $ad  =db('admin')->where('username', $data['username'])->find();
            if ($ad) {
                return json_data([], 300, '账号已存在');
            }
            $res=db('admin')->insertGetId($user);
            
            db('relation')->insertGetId(['role_id'=>$data['rule'], 'user_id'=>$res]);
            if ($res === false) {
                return json_data([], 300, '添加失败');
            }
            $this->log('添加了权限管理用户', $res . '/' . $data['username']);
            return json_data([], 200, '添加成功');
        }
        $da      =db('role')->select();
        $da1     =db('store')->select();
        $da3     =db('group_community')->where('pid',0)->select();
        $da2     =db('chanel')->where('type', 1)->select();
        $personal=db('personal')->where('status', 0)->select();
        return $this->fetch('add', ['da'=>$da, 'da1'=>$da1, 'da2'=>$da2, 'da3'=>$da3, 'personal'=>$personal]);
    }
    
    /**
     * @return array|mixed|string
     * 编辑管理
     */
    public function edit()
    {
        if ($data=Request::instance()->post()) {
            if ($data['rule'] == 9) {
                $mobile=$data['mobile'];
            } else{
                $mobile='';
            }
            $s =0;
            $s1=0;
            if (!empty($data['qu'])) {
                $s='';
                foreach ($data['qu'] as $key=>$val) {
                    $s.=$val . ',';
                }
                $s=substr($s, 0, - 1);
            }
            if (!empty($data['residential_id'])) {
                $s1='';
                foreach ($data['residential_id'] as $key=>$val) {
                    $s1.=$val . ',';
                }
                $s1=substr($s1, 0, - 1);
            }
            $user=[
                'username'      =>$data['username'],
                'created_time'  =>time(),
                'logo'          =>!empty($data['logo'])? $data['logo'] : '',
                'status'        =>0,
                'mobile'        =>$mobile,
                'store_id'      =>$data['store_id'],
                'qu'            =>$s,
                'hide'          =>$data['hide'],
                'residential_id'=>$s1,
                'export'        =>$data['export'],
                'personal_id'   =>empty($data['personal_id'])?0:$data['personal_id'],
            ];
            $res =db('admin')->where(['admin_id'=>$data['admin_id']])->update($user);
            $p   =db('relation')->where(['user_id'=>$data['admin_id']])->value('id');
            
            if (!empty($p)) {
                db('relation')->where(['user_id'=>$data['admin_id']])->update(['role_id'=>$data['rule']]);
                
            } else{
                db('relation')->insertGetId(['role_id'=>$data['rule'], 'user_id'=>$data['admin_id']]);
            }
            
            if ($res) {
                $this->log('修改了权限管理用户' . $data['admin_id'] . '/' . $data['username'], '');
                return json_data([], 200, '编辑成功');
            }
            
            return json_data([], 300, '编辑失败');
        }
        $admin_id=Request::instance()->get('admin_id');
        
        if (!$admin_id) {
            $this->error('请刷新后重试');
        }
        $res     =db('admin')
            ->where(['admin_id'=>$admin_id])
            ->find();
        $das     =db('relation')->where('user_id', $res['admin_id'])->value('role_id');
        $da      =db('role')->select();
        $da1     =db('store')->select();
        $da2     =db('chanel')->where('type', 1)->select();
        $personal=db('personal')->where('status', 0)->select();
        $da3     =db('group_community')->where('pid',0)->select();
        if (!empty($res['qu'])) {
            $res['qu']=explode(',', $res['qu']);
            foreach ($da2 as $k=>$item) {
                $da2[$k]['xuan']=2;
                foreach ($res['qu'] as $i) {
                    if ($item['id'] == $i) {
                        $da2[$k]['xuan']=1;
                    }
                    
                }
            }
        } else{
            foreach ($da2 as $k=>$item) {
                $da2[$k]['xuan']=2;
            }
        }
        if (!empty($res['residential_id'])) {
            $res['residential_id']=explode(',', $res['residential_id']);
            foreach ($da3 as $k=>$item) {
                $da3[$k]['xu']=2;
                foreach ($res['residential_id'] as $i) {
                    if ($item['group_id'] == $i) {
                        $da3[$k]['xu']=1;
                    }
                    
                }
            }
        } else{
            foreach ($da3 as $k=>$item) {
                $da3[$k]['xu']=2;
            }
        }
        
        return $this->fetch('edit', ['admin'=>$res, 'da'=>$da, 'das'=>$das, 'da1'=>$da1, 'da2'=>$da2, 'da3'=>$da3, 'personal'=>$personal]);
    }
    
    /**
     * 取消
     */
    public function del()
    {
        $store_id=Request::instance()->post();
        
        $res=false;
        if ($store_id) {
            $res=db('admin')->where(['admin_id'=>$store_id['label_id']])->update(['status'=>$store_id['state']]);
        }
        if ($res !== false) {
            $this->log('修改了权限管理用户', $store_id['label_id']);
            return json_data([], 200, '禁用成功');
        }
        return json_data([], 300, '禁用失败');
    }
    
    /**
     * @return mixed
     * 问题
     */
    public function category()
    {
        
        $data=db('role')->paginate(10);
        return $this->fetch('category', ['data'=>$data]);
    }
    
    /**
     * @return mixed
     * 修改
     */
    public function edi($id=0)
    {
        
        if ($data=Request::instance()->post()) {
            
            $use=[
                'role_name'=>$data['role_name'],
                'rule'     =>!empty($data['rule'])? substr($data['rule'], 0, - 1) : '*',
            
            ];
            
            $res=db('role')->where(['id'=>$data['id']])->update($use);
            if ($res === false) {
                return json_data([], 300, '编辑失败');
            }
            return json_data([], 200, '编辑成功');
        }
        $role_info=db('role')->where(['id'=>$id])->field('role_name')->find();
        return $this->fetch('edi', ['id'=>$id, 'role_name'=>$role_info['role_name']]);
    }
    
    public function role_edi($id)
    {
        $role_info=db('role')->where(['id'=>$id])->find();
        
        $autharrid=explode(',', $role_info['rule']);
        
        $node=cache('node');//去缓存
        if (!$node) {
            $node=db('node')->field('id,node_name,pId')->select();
        }
        
        foreach ($node as $k=>$item) {
            $node[$k]['checked']=0;
            foreach ($autharrid as $o) {
                if ($item['id'] == $o) {
                    $node[$k]['checked']=1;
                }
                
            }
            
        }
        
        return json_encode($node);
    }
    
    /**
     * @return mixed
     * 添加
     */
    public function ad()
    {
        
        if ($data=Request::instance()->post()) {
            
            $use=[
                'role_name'=>$data['role_name'],
                'rule'     =>!empty($data['rule'])? substr($data['rule'], 0, - 1) : '*',
            ];
            
            $res=db('role')->insertGetId($use);
            if ($res) {
                return json_data([], 200, '添加成功');
                
            }
            return json_data([], 300, '添加失败');
        }
        db('node')->cache('node')->field('id,node_name,pId')->select();
        $data=cache('node');//去缓存
        
        return $this->fetch('ad', ['data'=>$data]);
        
        
    }
    
    public function getMenuTestList()
    {
        
        
        $data=db('node')->field('id,node_name,pId')->select();
        foreach ($data as $k=>$l) {
            
            $p[$k]['id']  =$l['id'];
            $p[$k]['name']=$l['node_name'];
            $p[$k]['pId'] =$l['pId'];
        }
        
        
        return json_encode($p);
        
        
    }
    
    public function getMenuTestListEdit($id)
    {
        
        $admin    =db('admin')->where('admin_id', $id)->find();
        $autharrid=explode(',', $admin['personal_id']);
        $data=db('group_community')->field('group_id as id,username as name,pid as pId')->select();
        foreach ($data as $k=>$item) {
            $data[$k]['checked']=0;
            foreach ($autharrid as $o) {
                if ($item['id'] == $o) {
                    $data[$k]['checked']=1;
                }
                
            }
            
        }
        
        
        return json_encode($data);
        
        
    }
    
    /*
     * 集团公司
     */
    
    
    public function groupCommunity()
    {
        
        
        $data=db('group_community')->field('group_id,username,pid')->select();
        foreach ($data as $k=>$l) {
            
            $p[$k]['id']  =$l['group_id'];
            $p[$k]['name']=$l['username'];
            $p[$k]['pId'] =$l['pid'];
        }
        
        
        return json_encode($p);
        
        
    }
    
    /**
     * @return mixed
     * 删除
     */
    public function de()
    {
        $store_id=Request::instance()->post();
        if ($store_id) {
            $re=db('relation')->where(['role_id'=>$store_id['id']])->find();
            if ($re) {
                return json_data([], 300, '删除失败,请先用户');
            }
            $res=db('role')->where(['id'=>$store_id['id']])->delete();
            if ($res !== false) {
                return json_data([], 200, '删除成功');
            }
        }
        return json_data([], 300, '删除失败');
    }
    
    /**
     * @return mixed
     * 沟通记录
     */
    public function remote_index()
    {
        $data=db('node')->where('pId', 0)->paginate(30);
        return $this->fetch('remote_index', ['data'=>$data]);
    }
    
    /**
     * @return mixed
     * 修改
     */
    public function remote_edi()
    {
        if ($data=Request::instance()->post()) {
            $use=[
                'node_name'   =>$data['node_name'],
                'control_name'=>!empty($data['control_name'])? $data['control_name'] : '',
                'action_name' =>!empty($data['action_name'])? $data['action_name'] : '',
                'type_id'     =>!empty($data['type_id'])? $data['type_id'] : 0,
                'none'        =>!empty($data['none'])? $data['none'] : 0,
            
            ];
            
            $res=db('node')->where(['id'=>$data['id']])->update($use);
            if ($res === false) {
                return json_data([], 300, '编辑失败');
            }
            return json_data([], 200, '编辑成功');
        }
        $id  =Request::instance()->get('id');
        $type=Request::instance()->get('type');
        if (!$id) {
            $this->error('请刷新后重试');
        }
        $res=db('node')->where(['id'=>$id])
            ->find();
        
        return $this->fetch('remote_edi', ['data'=>$res, 'type'=>$type]);
        
    }
    
    /**
     * @return mixed
     * 添加
     */
    public function remote_ad($id)
    {
        
        if ($data=Request::instance()->post()) {
            
            $use=[
                'node_name'   =>$data['node_name'],
                'pId'         =>!empty($data['pId'])? $data['pId'] : 0,
                'control_name'=>!empty($data['control_name'])? $data['control_name'] : '',
                'action_name' =>!empty($data['action_name'])? $data['action_name'] : '',
                'type_id'     =>!empty($data['type_id'])? $data['type_id'] : 0,
                'none'        =>!empty($data['none'])? $data['none'] : 0,
            
            ];
            
            $res=db('node')->insertGetId($use);
            if ($res) {
                return json_data([], 200, '添加成功');
                
            }
            return json_data([], 300, '添加失败');
        }
        
        return $this->fetch('remote_ad', ['data'=>$id]);
        
        
    }
    
    /**
     * @return mixed
     * 删除
     */
    public function remote_de()
    {
        $store_id=Request::instance()->post();
        $re      =db('node')->where(['pId'=>$store_id['id']])->find();
        if ($re) {
            return json_data([], 300, '删除失败,请先删除子分类');
        }
        $res=false;
        if ($store_id) {
            $res=db('node')->where(['id'=>$store_id['id']])->delete();
        }
        if ($res !== false) {
            return json_data([], 200, '删除成功');
        }
        return json_data([], 300, '删除失败');
    }
    
    /**
     * @return mixed
     * 查看
     */
    public function remote_info($id=0)
    {
        
        
        if (!$id) {
            $this->error('请刷新后重试');
        }
        $res=db('node')
            ->where(['pId'=>$id,])
            ->paginate(10);
        return $this->fetch('remote_info', ['data'=>$res]);
        
    }
    
    private function log($content, $ord_id)
    {
        $user=$this->check_authority();
        $user=[
            'admin_id'  =>$user['admin_id'],
            'created_at'=>time(),
            'content'   =>$content,
            'ord_id'    =>$ord_id,
        
        ];
        
        db('log')->insertGetId($user);
        
    }
    
    /**
     * 重置密码
     */
    public function reset()
    {
        $admin_id=Request::instance()->post('admin_id');
        if (!$admin_id) {
            $this->result([], 300, '请刷新后重试');
        }
        $res=db('admin')->where(['admin_id'=>$admin_id])->update(['password'=>encrypt('123456')]);
        if ($res !== false) {
            return json_data([], 200, '密码已重置为：123456');
        }
        return json_data([], 300, '密码重置失败');
    }
    
    public function jp()
    {
        $data=Request::instance()->post();
        $res =db('admin')->where(['admin_id'=>$data['admin_id']])->update(['jp'=>1]);
        if ($res !== false) {
            return json_data([], 200);
        }
        return json_data([], 300);
    }
}
